package com.example.hanndlepermisstion;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        handlePermission();
    }

    /*让用户动态授权*/
    private void handlePermission() {
        // 检查是否已经授权

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) { //检查版本是否大于23
            int result = checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE); // 检查权限授予情况
            if (result == PackageManager.PERMISSION_GRANTED) {
                Log.e(TAG, "handlePermission:" + "已授权");
                return;//已授权，无需进一步授权
            } else {
                //如果没有授权，请求权限
                requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 101);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        Log.e(TAG, "onRequestPermissionsResult:");
        Toast.makeText(this, "读取外部文件的权限对于程序的正常运行至关重要！", Toast.LENGTH_SHORT).show();
    }
}